using Framework.Table;
using UniFramework.Utility;
using UnityEngine;

namespace Framework.UI
{
	public partial class LoginFrame : UIFrame
	{
		string userName = string.Empty;
		protected override string ActivedScene => "login_scene";

        void SetLoginUserName(string context)
		{
			InputUserName.onEndEdit.RemoveListener(this.OnInputUserNameEndEdit);
            InputUserName.text = context;
            InputUserName.onEndEdit.AddListener(this.OnInputUserNameEndEdit);
        }

        protected override void OnFrameOpen()
		{
			var lastLoginUserName = PlayerPrefs.GetString(PrefsKey.Login.LastLoginUserName);
            if (!string.IsNullOrEmpty(lastLoginUserName))
			{
				SetLoginUserName(lastLoginUserName);
				userName = lastLoginUserName;
            }
            EventDispatchManager.Instance.AddEvent(EventId.Game.EVENT_PLAYER_LOGINED, this.OnPlayerLogined);
        }
        protected override void OnFrameClose()
		{
            EventDispatchManager.Instance.RemoveEvent(EventId.Game.EVENT_PLAYER_LOGINED, this.OnPlayerLogined);
        }

        void OnPlayerLogined(IEventArgv eventArgv)
		{
			var package = YooAsset.YooAssets.GetPackage("DefaultPackage");
			if(null != package)
			{
				if(MainPlayer.RoleId == 0)
				{
                    package.LoadSceneAsync("scene_create_role");
                }
				else
				{
                    package.LoadSceneAsync("scene_actor_show");
                }
            }
            UIFrameManager.Instance.CloseFrame(this);
		}

        void OnBtnLoginClicked()
		{
			//Add Your Code Here
			if(string.IsNullOrEmpty(userName))
			{
				Debug.LogError("userName Is Empty !");
				return;
			}

			ClientNetManager.Create("127.0.0.1", 8900);
			PlayerPrefs.SetString(PrefsKey.Login.LastLoginUserName,userName);
            Net.SendReqLoginMessage(userName);
		}

		void OnInputUserNameEndEdit(string inputUserName)
		{
			//Add Your Code Here
			userName = inputUserName;
        }
	}
}
